#pragma once
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include "InetAddr.hpp"
#include "Log.hpp"

using namespace log_ns;

class Command {
    std::string Excute(const std::string& cmd) {
        FILE* fp = popen(cmd.c_str(), "r");
        if (fp) {
            std::string result;
            char info[1024];
            while (fgets(info, sizeof(info), fp)) {
                result += info;
            }
            pclose(fp);
            return result.empty() ? "success" : result;
        } else {
            LOG(WARNING, "open the fp fail\n");
            return "None";
        }
    }

public:
    Command() {}
    
    void CommandHandler(int sockfd, InetAdrr& who) {
        // 接收消息，然后返回消息    
        while (true) {
            // 开始读和写
            char buff[1024];
            // LOG(INFO, "the sockfd: %d\n", sockfd);
            int n = recv(sockfd, buff, sizeof(buff) - 1, 0);
            if (n > 0) {
                buff[n] = 0;
                LOG(DEBUG, "%s send a message: %s\n", who.AddrString().c_str(), buff);
                std::string result = Excute(buff);
                send(sockfd, result.c_str(), result.size(), 0);
            } else if (n == 0) {
                LOG(INFO, "client %s quit\n", who.AddrString().c_str());
                break;
            } else {
                LOG(FATAL, "read error, %s\n", strerror(errno));
                break;
            }
        }
    }
    
    ~Command() {}
};